package com.geeklan.smart.utils;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.geeklan.smart.R;

import java.io.IOException;
import java.util.HashMap;

public class VideoThumbnailLoader extends AsyncTask<String, Void, Bitmap> {
    private ImageView imageView;

    public VideoThumbnailLoader(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        String videoUrl = urls[0];
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        Bitmap bitmap = null;
        try {
            // 设置数据源（远程 URL）
            retriever.setDataSource(videoUrl, new HashMap<>());

            // 获取视频的某一帧（1000 毫秒处的预览图）
            bitmap = retriever.getFrameAtTime(1000000, MediaMetadataRetriever.OPTION_CLOSEST);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        }else {
            imageView.setImageResource(R.drawable.black_bg);
        }
    }
}

